<template>
    <div class="ant-input input-tag">
        <a-tag
            closable
            @close="onClose(index)"
            v-for="(item, index) in tagValue"
            :key="index"
        >{{ item }}</a-tag>
        <input class="input-tag-text" type="text" v-model="tagInputValue" @keyup="onKeyup($event)" />
    </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, withDefaults } from 'vue';

/**
 * 参数
 */
interface IProps {
    /**
     * 值 v0,v1,v2
     */
    modelValue: string | string[];

    /**分割符号 只有string类型下才可使用 */
    split?: string
}

const props = withDefaults(defineProps<IProps>(), {
    split: ","
});

const emits = defineEmits(['update:modelValue', 'change'])

const tagValue = ref<string[]>([]);

if (props.modelValue) {

    if (Array.isArray(props.modelValue)) {
        tagValue.value = props.modelValue;
    } else {
        tagValue.value = props.modelValue.split(props.split);
    }
}

const tagInputValue = ref<string>("");



const getRawValue = (): string | string[] => {

    if (Array.isArray(props.modelValue)) {
        return tagValue.value;
    }
    return tagValue.value.join(props.split);
};

// emit 触发
const changeEmit = () => {
    emits("change", getRawValue())
}

const onKeyup = (e: any) => {
    switch (e.keyCode) {
        case 8:
            if (tagInputValue.value == "") {
                tagValue.value.splice(tagValue.value.length - 1, 1);
            }
            changeValue();
            break;
        case 13:
            tagValue.value.push(tagInputValue.value);
            tagInputValue.value = "";
            changeValue();
            break;
    }
}



//点击删除时间触发
const onClose = (index: number) => {
    tagValue.value.splice(index, 1);
    changeEmit();
}


//更改值
const changeValue = () => {
    if (Array.isArray(props.modelValue)) {
        emits("update:modelValue", tagValue.value)
    } else {
        emits("update:modelValue", tagValue.value.join(props.split))
    }
    changeEmit();
}

</script>


<style scoped>
.input-tag {
    padding-left: 3px;
    display: flex;
    flex-wrap: wrap;
}
.input-tag > span {
    margin-right: 5px;
    margin-bottom: 2px;
}
.input-tag-text {
    border: 0;
    flex: 1;
    min-width: 80px;
    width: auto;
    max-width: 100%;
    font-size: 14px;
    line-height: 1.5715;
    padding-left: 11px;
    height: 22px;
}
.input-tag-text:focus {
    border: 0;
    outline: 0;
}
</style>